#ifndef __THREAD_HPP__
#define __THREAD_HPP__
#endif

#include <pthread.h>
#include <unistd.h>
#include <string>
#include <functional>

using namespace std;

namespace ThreadTest
{
    template<typename T>
    using func_t = function<void(T&)>;

    template<class T>
    class Thread
    {
    public:
        Thread(func_t<T> func, T& data, const string& thread_name = "none-name")
        :_func(func), _data(data), _thread_name(thread_name), _stop(true)
        {}

        ~Thread()
        {}

        static void* threadrountine(void* args)
        {
            Thread<T>* self = static_cast<Thread<T>*>(args);
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadrountine, this);
            //成功返回0，进入if
            if (!n)
            {
                //把_stop设为false，表示线程能被分离
                _stop = false;
                return true;
            }
            else
                return false;
        }

        //分离线程
        void Detach()
        {
            if (!_stop)
            {
                pthread_detach(_tid);
                _stop = true;
            }
        }

        void Join()
        {
            if (!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }

        string name()
        {
            return _thread_name;
        }

        void Stop()
        {
            _stop = true;
        }

        void Excute()
        {
            _func(_data);
        }
    private:
        string _thread_name;
        func_t<T> _func;
        T& _data;
        pthread_t _tid;
        bool _stop;
    };
}